import json
from flask import Flask, jsonify,Response,session
from flask import request,redirect,url_for,session
from fullstack.Models.Admin import Admin
from fullstack import app,api,db
from flask_restful import Resource


class LoginVue(Resource):
    def post(self):
        res=json.loads(request.data)
        # res=request.values
        print(res)
        resp = {'code': 200, 'msg': '登录成功'}
        username=res['username']
        password=res['password']
        session['username']=username
        # 设置session过期时间 一个月
        session.permanent=True
        # 查询数据库
        admin=Admin.query.filter_by(username=username).first()
        if not admin:
            resp['code']=-1
            resp['msg']="用户名不存在"
        # admin=Admin.query.first()        
        # 验证同户名和密码是否一致
        if admin.username==username and Admin.check_password(admin,password):
            return jsonify(resp)
        else:
            resp['code']=-2
            resp['msg']="密码错误"
            return jsonify(resp)
        
api.add_resource(LoginVue,'/vue/api/login')

class SigninVue(Resource):
    def post(self):
        res=json.loads(request.data)
        print(res)
        resp = {'code': 200, 'msg': '注册成功'}
        if not res['username'] or not res['password']:
            resp['code']=-1
            resp['msg']="请输入密码和用户名"
            return jsonify(resp)
        username=res['username']
        password=res['password']
        query=Admin.query.filter_by(username=username).first()
        if query:
            print(query)
            resp['code']=-2
            resp['msg']="用户名已存在，请重新输入"
            return jsonify(resp)
        admin=Admin()
        admin.username=username
        Admin.set_password(admin,password)
        db.session.add(admin)
        db.session.commit()
        return jsonify(resp)

api.add_resource(SigninVue,'/vue/api/signin')

# 测试用
class Test(Resource):
    def get(self):
        sql="SELECT * FROM admin"
        result=db.engine.execute(sql)
        for row in result:
            app.logger.info(row)

api.add_resource(Test,'/test')